<?php

namespace app\api\controller;

use app\admin\model\Branch;
use app\admin\model\Car;
use app\admin\model\CarOrder;
use app\admin\model\Code;
use app\admin\model\Form;
use app\admin\model\Log;
use app\admin\model\Package;
use app\admin\model\PriceLog;
use app\admin\model\RechargeSend;
use app\admin\model\Station;
use app\admin\model\Store;
use app\admin\model\User as UserModel;
use app\api\model\Order;
use app\BaseController;
use app\lib\MiniWechat;
use app\lib\tool\Str;
use app\Request;
use think\facade\Cache;
use app\api\model\CarBindStore as CarBindStoreModel;

class User extends BaseController
{

    public $isSuccessByDoor = false;

    // 无牌开门进车
    public function openDoorByNoLicensePlate(Request  $request)
    {
        if (!$request->auth)  return show(config('status.error'), '请登录');
        $userId = $request->uid;
        $stationId = $request->post('station_id', 0);
        $store_id = $request->post('store_id', 0);
        $manager_id = $request->post('manager_id', 0);
        $station = Station::find($stationId);
        if (empty($station)) return show(config('status.error'), '工位不存在');
        if ($station->status == 1) return show(config('status.error'), '该工位使用中，请更换其它工位或排队等候');
        if (empty($station->dev_id)) return show(config('status.error'), '请先配置卷闸门设备id');
        $store = Store::find($station->store_id);
        if (empty($store)) return show(config('status.error'), '门店不存在');
        if ($store->start_price <= 0 || $store->start_minutes <= 0 || $store->out_price <= 0) return show(config('status.error'), '该门店的价格信息设置不完善');
        // 检测有无余额
        $userBalacne = \app\admin\model\User::getBalacne($userId);
        // if ($userBalacne < $store->start_price) return show(config('status.error'), '您的余额不足以支付起步价，请先充值后再继续使用');
        if ($userBalacne <= 0) return show(config('status.error'), '您的余额不足，请先充值后再继续使用');
        $count = CarOrder::where('user_id', $userId)->where('is_pay',0)->count('id');
        if ($count > 0) {
             return show(config('status.error'), '您有未支付的订单，请支付后再进行此操作');
        }
        // 开门
        return $this->operateDoor(1, $userId, $station->id, $station->dev_id,  1, 1,0,$store_id,$manager_id);
    }

    // 开门出车
    public function openDoorByFinish(Request $request)
    {
        if (!$request->auth)  return show(config('status.error'), '请登录');
        $userId = $request->uid;
        $stationId = $request->post('station_id');
        $order = CarOrder::where([
            'station_id' => $stationId,
            'is_pay' => 0,
        ])->order('id desc')->findOrEmpty();

        $station = Station::find($stationId);
        if (empty($station)) return show(config('status.error'), '工位不存在');
        if ($station->status != 1) {
            return show(config('status.error'), '该工位空闲中，不可进行此操作');
        }
        if ($order->isEmpty()) {
            return show(config('status.error'), '该工位下暂无订单，无需操作');
            // 没有订单，直接开门
//            return $this->operateDoor(1, $userId, $stationId, $station->dev_id,  1, 2);
        }

        $order->pay_user_id = $request->uid;
        $price = $this->computedPrice($order);
        //洗完车根据商户处理扣费业务
        $recharge = \app\api\model\UserMerchantRecharge::where(['user_id'=>$userId,'manager_id'=>$order->manager_id])->findOrEmpty();
        if(empty($recharge->price) || $recharge->price<$price){
            return show(config('status.error'), '本次消费：' . $price . '元，您的余额不足，请先充值');
        }
        $recharge->price -= $price;
        $recharge->save();

        $user = \app\admin\model\User::where('id', $userId)->findOrEmpty();
        if ($user->price < $price) {
            return show(config('status.error'), '本次消费：' . $price . '元，您的余额不足，请先充值');
        }

        $user->price -= $price;
        $order->is_pay = 1;
        $order->price = $price;
        $order->end_time    = date('Y-m-d H:i:s');
        $station->status = 0;

        return $this->operateDoor(1, $userId, $stationId, $station->dev_id,  1, 2,0,0,0, function() use($station, $user, $order, $request, $price){
            $user->save();
            $order->save();
            $station->save();
            if ($order->recharge_send_id > 0) {
                RechargeSend::where('id', $order->recharge_send_id)->update([
                    'is_use' => 1,
                ]);
            }
            $count = PriceLog::create([
                'user_id' =>  $request->uid,
                'price'   => $price,
                'type'    => 2,
                'store_id' => $request->post('store_id', 0),
                'manager_id' => $request->post('manager_id', 0),
                'order_id' => $order->id
            ])->count();
            if ($count <=0 ) {
                PriceLog::create([
                    'user_id' =>  $request->uid,
                    'price'   => $price,
                    'type'    => 2,
                    'store_id' => $request->post('store_id', 0),
                    'manager_id' => $request->post('manager_id', 0),
                    'order_id' => $order->id
                ]);
            }
        });

    }

    public function getOrder()
    {
        $order = CarOrder::find(65);
        dump($this->computedPrice($order));
    }

    public function computedPrice($order)
    {
//        $order->pay_user_id = 23;
        $endTime = date('Y-m-d H:i:s');
        $useTime = strtotime($endTime) - strtotime($order->create_time);
        $station = Station::find($order->station_id);
        if (empty($station)){
            return show(config('status.error'), '工位不存在');
        }

        $store = Store::find($station->store_id);
        if (empty($store)){
            return show(config('status.error'), '门店不存在');
        }
        $startTimeLengh = $store->start_minutes * 60;
        $orderCount = CarOrder::where([
            'user_id' => $order->user_id,
            'is_first' => 1,
        ])->count('id');
        // 首次洗车
        if ($orderCount <= 0) {
            $order->is_first = 1;
            if ($store->first_user_pay_type == 1) {
                return 0;
            }
            if ($store->first_user_pay_type != 2) {
                goto Normal;
            } else {
                $startTimeLengh = $store->first_start_minutes * 60;
                if ($useTime <= $startTimeLengh) {
                    return $store->first_start_price;
                } else {
                    $outTime = round(($useTime - $startTimeLengh)  / 60, 2);
                    return $store->first_start_price + $outTime * $store->first_out_price;
                }
            }
        } else {
            Normal:
            // 查找有无赠送过的分钟数
            $send = RechargeSend::where([
                'user_id' => $order->pay_user_id,
                'is_use' => 0
            ])->findOrEmpty();
            if ($send->isEmpty()) { // 无可用的赠送分钟数
                if ($useTime <= $startTimeLengh) {
                    return $store->start_price;
                } else {
                    $outTime = round(($useTime - $startTimeLengh)  / 60, 2);
                    return $store->start_price + $outTime * $store->out_price;
                }
            } else { // 有赠送的分钟数
                if ($useTime <= $startTimeLengh) {
                    $order->recharge_send_id = $send->id;
                    return 0;
                } else {
                    // 赠送的时间转为秒数
                    $sendSecond = $send->send_min * 60;
                    if ($sendSecond >= $useTime) { // 赠送时间大于洗车时间，此次免费
                        $order->recharge_send_id = $send->id;
                        return 0;
                    } else {
                        $outTime = round(($useTime - $sendSecond)  / 60, 2);
                        return $outTime * $store->out_price;
                    }
                }
            }
        }

    }

    /**
     * @param $type 1 开门 0关门
     * @param $userId
     */
    public function operateDoor($type, $userId, $stationId, $devId, $carType, $scene = 1, $carId = 0, $store_id=0, $manager_id=0,$successCallback = null)
    {
        $log = Log::create([
            'user_id' => $userId,
            'type' => $type,
            'station_id' => $stationId,
            'scene' => $scene
        ]);

        // 操作门
        try {
            $accessToken = $this->getDoorToken();
        } catch (\Exception $e) {
            $log->content = '获取token失败';
            $log->save();
            return show(config('status.error'), $e->getMessage());
        }
        $result = $this->triggerOpenDoor($devId, $type, $accessToken);
        $log->content = json_encode($result);
        $log->save();
        file_put_contents("first_time.txt", $log->content.date('Y-m-d H:i:s')."\n\r", FILE_APPEND | LOCK_EX);
        $resultSuccess = $result['data']['result'] ?? false;
        if ($resultSuccess === 0) {
            success:
            $log->status = 1;
            $log->save();
            $this->isSuccessByDoor = true;
            //  开门的场景下顺便触发关门事件
            if ($scene == 1) {
                CarOrder::create([
                    'user_id' => $userId,
                    'type'    => $carType,
                    'car_id' =>  $carId,
                    'store_id' => $store_id,
                    'manager_id' => $manager_id,
                    'license' => Car::where('id', $carId)->value('license_plate'),
                    'station_id' => $stationId,
                ]);
//                Queue::later(1, CloseDoor::class, [
//                    'user_id' => $userId,
//                    'station_id' => $stationId,
//                    'dev_id' => $devId,
//                    'car_type' => $carType,
//                    'car_id' => $carId,
//                    'scene' => $scene
//                ]);
            }

            if ($scene == 1 && $type == 1) {
                // 进门将工位设为使用中
                Station::where('id', $stationId)->update([
                    'status' => 1
                ]);
            }elseif($scene == 2 && $type == 1) {
                // 关门将工位设为空闲中
//                Station::where('id', $stationId)->update([
//                    'status' => 0
//                ]);
            }

            if (is_callable($successCallback)) {
                $successCallback();
            }
            return show(config('status.success'), '操作成功');
        } elseif (in_array($resultSuccess, [-2, -3, -100, -500])) {
            try {
                $accessToken = $this->getDoorToken(false);
                $result = $this->triggerOpenDoor($devId, $type, $accessToken);
                $resultSucess = $result['data']['result'] ?? false;
                file_put_contents("second_time.txt", json_encode($result).date('Y-m-d H:i:s')."\n\r", FILE_APPEND | LOCK_EX);
                if ($resultSucess === 0) {
                    goto success;
                } else {
                    return show(config('status.error'), '开门失败，请重试或联系平台负责人!');
                }
            } catch (\Exception $e) {
                $log->content = '二次获取token失败';
                $log->save();
                return show(config('status.error'), $e->getMessage());
            }
        } else {
            return show(config('status.error'), '开门失败，请重试或联系平台负责人' . $resultSuccess);
        }
    }

    public function triggerOpenDoor($devId, $type, $accessToken)
    {
        $requestData = [
            'request' => ['apiVer' => '1.0.0'],
            'version' => '1.0',
            'id' => date('YmdHis') . rand(10000, 99999),
            'params' => [
                'action' => 'actionDeviceRemoteCtrl',
                'devid' => $devId,
                'curtainConrtol' => $type,
                'appKey' =>  env('DEVICE.appKey'),
                'accessToken' => $accessToken
            ]
        ];
        $url = 'http://' . env('DEVICE.hostname') . '/a123otvyhPKCu0zG/bf9pzP3AhEscFq';
        $result = curl($url, $requestData);
        return $result;
    }

    /**
     * 获取token
     * @param bool $isUseCache
     * @return false|mixed|object|\think\App
     * @throws \Exception
     */
    private function getDoorToken($isUseCache = true)
    {
        $dorrTokenName = 'door_token';
        $token = cache($dorrTokenName);
        if (!empty($token) && $isUseCache) return $token;
        $time = time();

        // 获取令牌
        $data  = [
            'request' => ['apiVer' => '1.0.0'],
            'version' => '1.0',
            'id' => date('YmdHis') . rand(10000, 99999),
            'params' => [
                'action' => 'GetAccesstoken',
                'appKey' => env('DEVICE.appKey'),
                'ts' => $time,
                'signature' => $this->getSingnatore($time),
            ]
        ];

        $url = 'http://' . env('DEVICE.hostname') . '/a123otvyhPKCu0zG/bfdVUtU2fR7SrW';
        $result = curl($url, $data);
        $token = $result['data']['tokeninfo']['token'] ?? false;
        if (empty($token)) {
            throw new \Exception('获取厂家认证标识失败，请重新尝试，若无效请联系管理员');
        }

        cache('door_token', $token, 86400 & 10);
        return $token;
    }

    public function getSingnatore($ts)
    {
        $content = 'appKey=' . env('DEVICE.appKey') . '&ts=' . $ts .'&' . env('DEVICE.appSecret');
        return base64_encode(hash_hmac('sha1', $content, env('DEVICE.appSecret'), true ));
    }

    /**
     * 创建订单
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function createOrder(Request $request)
    {
        $pgId = $request->post('package_id');
        $package = Package::find($pgId);
        if (empty($package)) {
            return show(config('status.error'), '套餐不存在');
        }
        $store_id = $request->post('store_id');
        if (empty($store_id)) {
            return show(config('status.error'), '门店id不允许为空');
        }
        $manager_id = $request->post('manager_id');
        if (empty($manager_id)) {
            return show(config('status.error'), '商户id不允许为空');
        }
//        $order = Order::where([
//            'user_id' => $request->uid,
//            'is_pay' => 0,
//        ])->find();
//        if (empty($order)) {
//            $order = new Order();
//            $order->user_id = $request->uid;
//            $order->order_num = buildOrderNum();
//        }
        $order = new Order();
        $order->user_id = $request->uid;
        $order->order_num = buildOrderNum();
        $order->price = $package->price;
        $order->pg_id = $pgId;
        $order->send_price = $package->send_price;
        $order->price = $package->price;
        $order->wechat_order_num = buildOrderNum('wx');
        $order->store_id = $store_id;
        $order->manager_id = $manager_id;
        $manager = \app\admin\model\Manager::find(['id'=>$manager_id]);
        if(empty($manager['mch_id']) || empty($manager['mch_key'])){
            return show(config('status.error'), '请联系管理员配置商户支付信息mch_id、mch_key');
        }
        $wechat = new MiniWechat($manager['mch_id'],$manager['mch_key']);

        $result = $wechat->createOrder([
            'body' => '充值',
            'out_trade_no' => $order->wechat_order_num,
            'openid' => \app\admin\model\User::where('id', $request->uid)->value('openid'),
            'total_fee' => round($order->price * 100),
            'trade_type' => 'JSAPI',
            'notify_url' => request()->domain() . '/api/pay/wechatNotifyByPackagePay',
            'spbill_create_ip' => '127.0.0.1',
        ]);
        $order->create_time = date('Y-m-d H:i:s');
        $order->wechat_placeorder_res_data = json_encode($result);
        $order->save();

        return show(config('status.success'), '操作成功',
            $result
        );
    }

    // 我的余额
    public function getMyBalances(Request  $request)
    {
        if (!$request->auth)  return show(config('status.error'), '请登录');
        $userId = $request->uid;
        $where['user_id'] = $userId;
        $type = $request->post('type');
        if(!empty($type)){
            if(strpos($type,',') !== false){
                $where['type'] = explode(',',$type);
            }else{
                $where['type'] = $type;
            }
        }
        $user = \app\admin\model\User::find($userId);
        $list = PriceLog::alias('pl')->field('pl.*,s.name storename')->join('store s','pl.store_id=s.id','left')
            ->where($where)
            ->order('pl.id desc')->select();
        /*$list = PriceLog::where([
            'user_id' => $userId
        ])->order('id desc')
            ->select();*/

        return show(config('status.success'), 'success', [
            'price' => $user->price,
            'list' => $list
        ]);
    }

    // 兑换余额
    public function exchangePrice(Request  $request)
    {
        if (!$request->auth)  return show(config('status.error'), '请登录');
        $code = $request->post('code');
        $store_id = $request->post('store_id');
        $manager_id = $request->post('manager_id');
       $result =  \app\admin\model\CarBindStore::findOrEmpty(['user_id'=>$request->uid,'store_id'=>$store_id]);
       if(empty($result)){
           return show('-2','您还没有绑定该门店，请前往绑定');
       }
        $codeObj = Code::where('code', $code)->where('status', 0)->find();
        if (empty($codeObj)) return show(-1, '该兑换码不存在或已被兑换');
        $codeObj->status = 1;
        $codeObj->exchange_time = date('Y-m-d H:i:s');
        $codeObj->save();
        $price = PriceLog::create([
            'user_id' =>  $request->uid,
            'price'   => $codeObj->price,
            'store_id' => $store_id,
            'manager_id' => $manager_id,
            'type'    => 3,
        ]);
        $result = \app\api\model\UserMerchantRecharge::changeRecord(['user_id'=>$request->uid,'price'=>$codeObj->price,'manager_id'=>$manager_id,'send_price'=>0]);
        \app\admin\model\User::where('id', $request->uid)->inc('price', $codeObj->price)->update();

        return show(config('status.success'), 'success');
    }

    public function login()
    {
        $mini = new MiniWechat;
        $data = $mini->code2Session(input('code', ''));
        if (!is_array($data) || !array_key_exists('session_key', $data) || !array_key_exists('openid', $data) ) {
            return show($data['errcode'], '微信获取信息失败：' . $data['errmsg']);
        }

        $openId = $data['openid'];
//        $openId = 'oSCT25YW5sDE8piiJArc27Q5o1W8';
        $userInfo = UserModel::where('openid', $openId)->find();
        if (!empty($userInfo)) {
            $userInfo->wxname = input('post.wxname');
            $userInfo->wximage = input('post.wximage');
            $userInfo->save();
        } else {
            $userInfo = UserModel::create([
                'wxname' => input('post.wxname'),
                'wximage'=> input('post.wximage'),
                'openid' => $openId,
                'phone'  => ''
            ]);
        }
        $userInfo = $userInfo->toArray();
        $userInfo['session_key'] = $data['session_key'];
        $token = Str::getToken();
        Cache::set(config('cache.stores.redis.prefix') . $token, $userInfo, config('cache.stores.redis.timeout'));
        return show(config('status.success'), '登录成功', ['token' => $token]);
    }

    // 我的车辆
    public function getCarList(Request  $request)
    {
         if (!$request->auth)  return show(config('status.error'), '请登录');
        $carS = Car::where('user_id', $request->uid)->select();
        if(!empty($carS)){
            foreach($carS as $item){
                $bindNum = CarBindStoreModel::where(['car_id'=>$item->id])->count('id');
                $item->binds = $bindNum? $bindNum:0;
            }
        }
        return show(config('status.success'), '操作成功', $carS);
    }

    // 绑定车辆
    public function bindCar(Request  $request)
    {
        if (!$request->auth)  return show(config('status.error'), '请登录');
        $type = $request->post('type');
        $name = $request->post('name');
        $phone = $request->post('phone');
        $store_id = $request->post('store_id');
        $manager_id = $request->post('manager_id');
        if(empty($store_id)){
            return show(config('status.error'), '门店id不允许为空');
        }
        if(empty($manager_id)){
            return show(config('status.error'), '商户id不允许为空');
        }

        $licensePlate = $request->post('license_plate');
        if (empty($name)) return show(config('status.client_error'), '姓名不能为空');
        if (empty($name)) return show(config('status.client_error'), '姓名不能为空');
        if (empty($phone)) return show(config('status.client_error'), '手机号不能为空');
        $car = Car::where('license_plate', $licensePlate)->field('id')->find();
        if (!empty($car)) return show(config('status.error'), '该车牌号已被绑定');
        $car = new Car();
        $id = $car->insertGetId([
            'user_id' => $request->uid,
            'type' => $type,
            'name' => $name,
            'phone' => $phone,
            'store_id'=>$store_id,
            'manager_id'=>$manager_id,
            'license_plate' => $licensePlate,
        ]);
        $carData = [
            'car_id'=>$id,
            'user_id'=>$request->uid,
            'store_id'=>$store_id,
            'manager_id'=>$manager_id,
        ];
        CarBindStoreModel::create($carData);
        return show(config('status.success'), '操作成功');
    }

    // 修改车辆
    public function updateCar(Request  $request)
    {
        if (!$request->auth)  return show(config('status.error'), '请登录');
        $car = Car::where(['user_id' => $request->uid, 'id' => $request->post('id')])->find();
        if (empty($car)) return show(config('status.error'), '未绑定的车辆');
        $type = $request->post('type');
        $name = $request->post('name');
        $phone = $request->post('phone');
        $licensePlate = $request->post('license_plate');
        if (empty($name)) return show(config('status.client_error'), '姓名不能为空');
        if (empty($phone)) return show(config('status.client_error'), '手机号不能为空');
        if ($licensePlate != $car->license_plate) {
            $car = Car::where('license_plate', $licensePlate)->whereNotIn('id', [$car->id])->field('id')->find();
            if (!empty($car)) return show(config('status.error'), '该车牌号已被绑定');
        }

        Car::where('id' , $request->post('id'))->update([
            'type' => $type,
            'name' => $name,
            'phone' => $phone,
            'license_plate' => $licensePlate,
        ]);

        return show(config('status.success'), '操作成功');
    }

    public function deleteCar(Request $request)
    {
        if (!$request->auth)  return show(config('status.error'), '请登录');
        Car::where('id', $request->post('id'))->delete();
        return show(config('status.success'), '操作成功');
    }

    /**
     * 报名列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(Request  $request)
    {
        $page = $request->post('page', 1);
        $limit = $request->post('limit', 10);
        $branch = $request->post('branch');
        $model = Form::order('id desc')->where('user_id', $request->uid);
        if (!empty($branch)) {
            $model->where([
                'branch' => $branch
            ]);
        }
        $list = $model->page($page, $limit)->select();
        $model2 = Form::where('user_id', $request->uid);
        if (!empty($branch)) {
            $model2->where([
                'branch' => $branch
            ]);
        }
        $count = $model2->count('id');

        return show(config('status.success'), 'success', ['list' => $list, 'count' => $count]);
    }


    /**
     * 报名
     * @param Request $request
     * @return \think\response\Json
     */
    public function createRecord(Request $request)
    {
        $name = $request->post('name');
        $sex = $request->post('sex');
        $idCard = $request->post('idcard');
        $phone = $request->post('phone');
        if (mb_strlen($name) < 2) {
            return show(config('status.client_error'), '姓名格式不正确');
        }
        if (!in_array($sex, ['男', '女'])) {
            return show(config('status.client_error'), '性别格式不正确');
        }
        if (!$this->regexpMatchIdCard($idCard)) {
            return show(config('status.client_error'), '身份证格式不正确');
        }
        if (strlen($phone) != 11) {
            return show(config('status.client_error'), '手机号格式不正确');
        }
        $model = new Form();
        $model->name = $name;
        $model->sex = $sex;
        $model->idcard = $idCard;
        $model->phone = $phone;
        $model->user_id = $request->uid;
        $fields = ['department', 'work', 'company', 'branch', 'branch_id', 'branch_office'];
        foreach ($fields as $field) {
            $model->$field = $request->post($field);
        }

        $model->save();

        return show(config('status.success'), 'success');
    }

    /**
     * 报名
     * @param Request $request
     * @return \think\response\Json
     */
    public function update(Request $request)
    {
        $name = $request->post('name');
        $sex = $request->post('sex');
        $idCard = $request->post('idcard');
        $phone = $request->post('phone');
        if (mb_strlen($name) < 2) {
            return show(config('status.client_error'), '姓名格式不正确');
        }
        if (!in_array($sex, ['男', '女'])) {
            return show(config('status.client_error'), '性别格式不正确');
        }
        if (!$this->regexpMatchIdCard($idCard)) {
            return show(config('status.client_error'), '身份证格式不正确');
        }
        if (strlen($phone) != 11) {
            return show(config('status.client_error'), '手机号格式不正确');
        }
        $model =  Form::find($request->post('id'));
        if (empty($model)) {
            return show(config('status.client_error'), '记录不存在');
        }
        $model->name = $name;
        $model->sex = $sex;
        $model->idcard = $idCard;
        $model->phone = $phone;
        $fields = ['department', 'work', 'company', 'branch', 'branch_id', 'branch_office'];
        foreach ($fields as $field) {
            $model->$field = $request->post($field);
        }

        $model->save();

        return show(config('status.success'), 'success');
    }

    /**
     * 获取分会
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getBranchs()
    {
        return show(config('status.success'), 'success', Branch::order('sort desc id desc')->select());
    }

    public function getUserInfo(Request $request)
    {
        if (!$request->auth)  return show(config('status.error'), '请登录');
        $user = \app\api\model\User::field('id,wxname,wximage,price')->where('id', $request->uid)->find();
        if (empty($user)) {
            return show(config('status.success'), 'success', []);
        }
        if (empty($user->wxname))  $user->wxname='';
        if (empty($user->wximage)) $user->wximage='';
        $user->car_count = Car::where('user_id', $request->uid)->count();
        return show(config('status.success'), 'success', $user);
    }

    // 更新用户信息
    public function updateUserInfo(Request  $request)
    {
        \app\api\model\User::field('id,wxname,wximage')->where('id', $request->uid)->update([
            'wxname' => $request->post('wxname'),
            'wximage' => $request->post('wximage'),
        ]);
        return show(config('status.success'), 'success');
    }

    /**
     * 校验身份证号码是否合法
     * @param $str
     * @param bool $getBasicInfo 是否提取身份证号码中的基本信息(出生日期/性别)
     * @return mixed
     */
    public function regexpMatchIdCard($str, $getBasicInfo = false)
    {
        //校验身份证位数和出生日期部分
        $pattern = "/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/";
        preg_match($pattern, $str, $match);
        $result = $match ? true : false;
        if (!$result) {
            return false;
        }

        //校验前两位是否是所有省份代码
        $province_code = ['11', '12', '13', '14', '15', '21', '22', '23', '31', '32', '33', '34', '35', '36', '37', '41', '42', '43', '44', '45', '46', '50', '51', '52', '53', '54', '61', '62', '63', '64', '65', '71', '81', '82', '91'];
        if (!in_array(substr($str, 0, 2), $province_code)) {
            return false;
        }

        //校验身份证最后一位
        $ahead17_char = substr($str, 0, 17);
        $last_char = substr($str, -1);
        $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); // 前17位的权重
        $c = array(1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2); //模11后的对应校验码
        $t_res = 0;
        for ($i = 0; $i < 17; $i++) {
            $t_res += intval($ahead17_char[$i]) * $factor[$i];
        }
        $calc_last_char = $c [$t_res % 11];
        if ($last_char != $calc_last_char) {
            return false;
        }

        if (!$getBasicInfo) {
            return $result;
        }

        //从身份证号码中提取出生日期和性别
        $birth_year = substr($str, 6, 4);
        $birth_month = substr($str, 10, 2);
        $birth_day = substr($str, 12, 2);
        if (!checkdate($birth_month, $birth_day, $birth_year)) {
            return false;
        }
        $brithday = $birth_year . "-" . $birth_month . "-" . $birth_day;
        $gender_char = substr($str, -2, 1);
        if ($gender_char % 2 == 0) {
            $gender = 2; //女
        } else {
            $gender = 1; //男
        }

        return [
            'birthday' => $brithday,
            'age' => self::getAge(strtotime($brithday)),
            'gender' => $gender,
        ];
    }

    /**
     * 根据出生日期获取年龄
     * @param string $birthday 出生日期时间戳
     * @return false|string
     */
    public static function getAge($birthday)
    {
        //格式化出生时间年月日
        $byear = date('Y', $birthday);
        $bmonth = date('m', $birthday);
        $bday = date('d', $birthday);

        //格式化当前时间年月日
        $tyear = date('Y');
        $tmonth = date('m');
        $tday = date('d');

        //计算年龄
        $age = $tyear - $byear;
        if ($bmonth > $tmonth || $bmonth == $tmonth && $bday > $tday) {
            $age--;
        }
        return $age;
    }


    public  function  test(){
       /* $manager = \app\admin\model\Manager::where(['mch_id'=>'1605231613'])->find();
        echo \app\admin\model\Manager::getLastSql();
        var_dump($manager['mch_id']);exit();*/
        $xml = '<xml><appid><![CDATA[wx09280ebcd19ff489]]></appid>
<bank_type><![CDATA[OTHERS]]></bank_type>
<cash_fee><![CDATA[5000]]></cash_fee>
<fee_type><![CDATA[CNY]]></fee_type>
<is_subscribe><![CDATA[N]]></is_subscribe>
<mch_id><![CDATA[1627251397]]></mch_id>
<nonce_str><![CDATA[2sij9i5yyz4auo9wupxm3f0l1qkvm0y9]]></nonce_str>
<openid><![CDATA[o26gj483xeNV1Ogph9Kx5qfC8pF0]]></openid>
<out_trade_no><![CDATA[wx2022080920463598574850]]></out_trade_no>
<result_code><![CDATA[SUCCESS]]></result_code>
<return_code><![CDATA[SUCCESS]]></return_code>
<sign><![CDATA[157473571D76F8668BF423EDF884A933]]></sign>
<time_end><![CDATA[20220809204640]]></time_end>
<total_fee>5000</total_fee>
<trade_type><![CDATA[JSAPI]]></trade_type>
<transaction_id><![CDATA[4200001432202208095819031205]]></transaction_id>
</xml>';
        $data = \WeChat\Contracts\Tools::xml2arr($xml);
        var_dump($data['mch_id']);
        print_r($data);exit();
        $result = \app\api\model\UserMerchantRecharge::changeRecord(['user_id'=>20,'price'=>100,'manager_id'=>20,'send_price'=>0]);
        file_put_contents("second_time.txt", json_encode($result).date('Y-m-d H:i:s')."\n\r", FILE_APPEND | LOCK_EX);
        var_dump($result);exit();
        $orderNum ='wx2022081810124499100529';
        $order = Order::where('wechat_order_num', $orderNum)->find();
        $result = \app\api\model\UserMerchantRecharge::changeRecord($order);
        var_dump($result);exit();
    }
}
